/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/* $Id: psmisc.c 31 2007-06-27 02:27:21Z kf701.ye $ */

#include "kf701.h"

#include <sys/types.h>
#include <dirent.h>
#include <ctype.h>
#include <libgen.h>

/**
 * @brief find a proc's pid
 * @param pname proc name
 * @return the pid of pname or -1 on error
 */
pid_t pidof( const char *pname )
{
	int pid = -1;
	DIR *dir = opendir("/proc");
	if( NULL == dir )
	{
		goto exit;
	}
	char path_buf[128];
	char name_buf[128];
	struct dirent *de = NULL;
	while( (de = readdir(dir)) )
	{
		if( de->d_type != DT_DIR )
			continue;
		if( !isdigit(de->d_name[0]) )
			continue;
		sprintf( path_buf, "/proc/%s/exe", de->d_name );
		if( readlink( path_buf, name_buf, sizeof(name_buf) ) <= 0 )
			continue;
		if( strstr( basename(name_buf), pname ) )
		{
			pid = atoi( de->d_name );	
			break;
		}
	}
	closedir( dir );
exit:
	return pid;
}
